from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from Crypto.Cipher import ARC4 as Crypter
import base64
import random
import sys

def regenerateKeyMarker():
    crypt_key = base64.b64encode(repr(random.uniform(1, 1000)))
    crypt_marker = base64.b64encode(repr(random.uniform(1, 1000)))
    return crypt_key, crypt_marker 

class Keyring(object):
    
    def __init__(self, size=5):
        self.size = size
        self._data = []
        for i in xrange(size):
            self.rotate()
         
    def __iter__(self):
        for item in self._data:
            yield item

    def clear(self):
        for i in range(len(self._data)):
            self._data[i]=None

    def rotate(self):
        if len(self._data) == self.size:
            self._data.pop()
        self._data.insert(0, regenerateKeyMarker())

    @property
    def current(self):
        return self._data[0]


# initialize keyring immediatly
keyring = Keyring(14)

# ARC4/XOR require two instances to encode/decode
def encrypt(source, key):
    return Crypter.new(key).encrypt(source)

def decrypt(source, key):
    return Crypter.new(key).decrypt(source)

def decodeData(source, delimiter='\n'):
    #import pdb; pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__).set_trace()
    for keymarkerPair in keyring:
        try:
            source_decoded = base64.b64decode(source)
            values = decrypt(source_decoded, keymarkerPair[0]).split(delimiter)
            if values[0] == keymarkerPair[1]: 
                return tuple(values[1:])
        except:
            break 
    return None

def encodeData(values, delimiter='\n'):
    #import pdb; pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__).set_trace()
    data = ''
    values = list(values)
    values.insert(0, keyring.current[1])
    for i in xrange(len(values)):
        if i > 0:
             data += delimiter
        data += str(values[i])
    return base64.b64encode(encrypt(data, keyring.current[0]))


class GenkeysPage(webapp.RequestHandler):
    
    def __init__(self, *args, **kwargs):
        super(GenkeysPage, self).__init__(*args, **kwargs)

    def get(self):
        self.post()

    def post(self):
        keyring.rotate()
        #import pdb; pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__).set_trace()

application = webapp.WSGIApplication([
    ('/genkeys', GenkeysPage),
], debug=True)

def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()   
